<?php
/**
 * This file houses the DocOutputProtocol class.
 *
 * Copyright (c) 2010, Kalkomey Enterprises, Inc.
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 * 
 * - Redistributions of source code must retain the above copyright notice, this list
 *   of conditions and the following disclaimer.
 * - Redistributions in binary form must reproduce the above copyright notice, this 
 *   list of conditions and the following disclaimer in the documentation and/or other
 *   materials provided with the distribution.
 * - Neither the name of the Kalkomey Enterprises, Inc. nor the names of its 
 *   contributors may be used to endorse or promote products derived from this 
 *   software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
 * SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, 
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
 * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
 * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 * 
 * @license http://www.opensource.org/licenses/bsd-license.php New BSD License
 * @copyright Copyright (c) 2010, Kalkomey Enterprises, Inc.
 * @link http://code.google.com/p/swerv/
 * @package Shared
 * @subpackage Protocols
 */

/**
 * The DocOutputProtocol object is used to display auto-generated documentation based on reflection and DocBlock comments of controllers, request objects, response objects, and models.
 * Note that this object is tightly coupled to the MainController in the shared directory.  This controller should not be overridden in your apps, nor should it be modified.  It is used strictly to display the documentation.
 *
 * @package Shared
 * @subpackage Protocols
 */
class DocOutputProtocol extends OutputProtocol {
	
	/**
	 * A view object - used to display the documentation.
	 * @var View
	 */
	private $view;
	
	/**
	 * Object constructor.
	 *
	 * @return DocOutputProtocol
	 */
	public function __construct() {
		$this->view = new View();
	}
	
	/**
	 * Returns documentation in HTML form.
	 *
	 * @uses $paths['framework']
	 * @uses $apps
	 * @uses SiteContext::$controller
	 * @uses SiteContext::$action
	 * @uses SiteContext::$params
	 * @uses View::setVar()
	 * @uses View::setView()
	 * @uses View::render()
	 * @uses DocOutputProtocol::getInputTypes()
	 * @uses DocOutputProtocol::getControllers()
	 * @uses DocOutputProtocol::getDataTypes()
	 * @uses DocOutputProtocol::getSchema()
	 * @uses ClassReflector::reflect()
	 * @uses StringUtility::toPascalCase()
	 */
	public function getOutput(&$data) {
		global $paths;
		$controller = SiteContext::$controller;
		$action = SiteContext::$action;
		$nonExtendedTypes = array (
			'int',
			'integer',
			'string',
			'bool',
			'boolean',
			'float',
			'double',
		);
		$this->view->setVar('nonExtendedTypes', $nonExtendedTypes);
		$inputTypes = array();
		$schemas = array();
		$this->getInputTypes($paths['shared']['protocols'], $inputTypes);
		$this->getInputTypes($paths['app']['protocols'], $inputTypes);
		$this->getSchemas($paths['shared']['protocols'], $schemas);
		$this->getSchemas($paths['app']['protocols'], $schemas);
		$this->view->setVar('inputTypes', $inputTypes);
		$this->view->setVar('schemas', $schemas);
		ksort($inputTypes);
		// we want to display all of the available controllers and actions and data types
		if ($controller == 'MainController' && $action == 'index') {
			$controllers = array();
			$requests = array();
			$responses = array();
			$models = array();

			$this->getControllers($paths['shared']['controllers'], $controllers);
			$this->getControllers($paths['app']['controllers'], $controllers);

			$this->getDataTypes($paths['shared']['requests'], $requests);
			$this->getDataTypes($paths['app']['requests'], $requests);

			$this->getDataTypes($paths['shared']['responses'], $responses);
			$this->getDataTypes($paths['app']['responses'], $responses);

			$this->getDataTypes($paths['shared']['models'], $models);
			$this->getDataTypes($paths['app']['models'], $models);
		
			ksort($controllers);
			ksort($requests);
			ksort($responses);
			ksort($models);
		
			$this->view->setVar('controllers', $controllers);
			$this->view->setVar('requests', $requests);
			$this->view->setVar('responses', $responses);
			$this->view->setVar('models', $models);
			$this->view->setView('main_index.php');
		} elseif ($controller != 'MainController' && $action == 'index') {
			$reflector = new ClassReflector($controller);
			$controller = $reflector->reflect();
			$this->view->setVar('controller', $controller);
			$this->view->setView('controller.php');
		} elseif ($controller == 'MainController' && $action == 'type') {
			$className = SiteContext::$params[0];
			$reflector = new ClassReflector($className);
			$arr = $reflector->reflect();
			$this->view->setVar('arr', $arr);
			$this->view->setView('type.php');
		} elseif ($controller == 'MainController' && $action == 'schema') {
			$schemaType = SiteContext::$params[0];
			$requestedController = SiteContext::$params[1];
			$requestedAction = SiteContext::$params[2];
			$className = StringUtility::toPascalCase(strtolower($schemaType) . '_schema');
			$obj = new $className();
			$schema = $obj->getSchema($requestedController, $requestedAction);
			return $schema;
		}
		return $this->view->render();
	}
	
	/**
	 * Builds a list of all the available protocols (except for doc).
	 * Note: this is a recursive method.
	 *
	 * @param string $path the path to scan for protocols
	 * @param array &$inputTypesArr the array of protocols to add to
	 *
	 * @return void
	 */
	private function getInputTypes($path, array &$inputTypesArr) {
		if (is_dir($path)) {
			foreach (new DirectoryIterator($path) as $file) {
				$filename = $file->getFilename();
				if (!$file->isDot() && $file->isDir() && $filename != 'doc' && strpos($filename, '.') === false) {
					$inputTypesArr[] = $filename;
				}
			}
		}
	}
	
	/**
	 * Builds an array of all the controllers found in a given path, including their reflection data.
	 * Note: this is a recursive method.
	 *
	 * @param string $path the path to scan for controllers
	 * @param array &$controllersArr the array of controllers to add to
	 *
	 * @return void
	 */
	private function getControllers($path, array &$controllersArr) {
		foreach (new DirectoryIterator($path) as $file) {
			$filename = $file->getFilename();
			if (!$file->isDot() && strpos($filename, '.php') !== false) {
				$className = str_replace('.php', '', $filename);
				$reflector = new ClassReflector($className, $path . '/' . $filename);
				$controllersArr[$className] = $reflector->reflect();
			}
		}
	}
	
	/**
	 * Builds an array of all the data types (requests, responses, or models) found in a given path, including their reflection data.
	 * Note: this is a recursive method.
	 *
	 * @param string $path the path to scan for data types
	 * @param array &$dataTypesArr the array of data types to add to
	 *
	 * @return void
	 */
	private function getDataTypes($path, array &$dataTypesArr) {
		foreach (new DirectoryIterator($path) as $file) {
			$filename = $file->getFilename();
			if ($file->isDir() && !$file->isDot()) {
				$this->getDataTypes($path . '/' . $filename, $dataTypesArr);
			} elseif (!$file->isDot() && strpos($filename, '.php') !== false && strpos($filename, '.svn') === false) {
				$className = str_replace('.php', '', $filename);
				$reflector = new ClassReflector($className, $path . '/' . $filename);
				$dataTypesArr[$className] = $reflector->reflect();
			}
		}
	}
	
	/**
	 * Builds an array of all the schemas in a given path.
	 * Note: this is a recursive method.
	 *
	 * @param string $path the path to scan for schemas
	 * @param array &$schemas the array of schemas to add to
	 *
	 * @return void
	 */
	private function getSchemas($path, array &$schemas) {
		foreach (new DirectoryIterator($path) as $file) {
			$filename = $file->getFilename();
			if ($file->isDir() && !$file->isDot()) {
				$this->getSchemas($path . '/' . $filename, $schemas);
			} elseif (!$file->isDot() && strpos($filename, 'Schema.php') !== false && strpos($filename, '.svn') === false) {
				$schemas[] = strtoupper(str_replace('Schema.php', '', $filename));
			}
		}
	}
	
}
